package com.sky.controller.user;


import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.exception.NullParamsException;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@Api(tags = "C端菜品相关接口")
@RestController("userDishController")
@RequestMapping("/user/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询启售的菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("C端根据分类id查询菜品")
    public Result<List<DishVO>> getDishByCategoryId (Long categoryId) {
        log.info("C端根据分类id查询菜品:{}",categoryId);
        // 构造redis中的key
        String key = "dish_" + categoryId;
        List<DishVO> dishes = (List<DishVO>) redisTemplate.opsForValue().get(key);
        // 判断redis中有无数据
        if (dishes != null && dishes.size() > 0) {
            // 如果存在，则返回数据
            log.info("成功返回Redis缓存数据");
            return Result.success(dishes);
        }

        if (categoryId == null) {
            throw new NullParamsException(MessageConstant.NOT_ALLOW_DATA);
        }
        dishes = dishService.qaueryDishAndFlavorByCategoryId(categoryId);
        // 往redis中回写数据
        redisTemplate.opsForValue().set(key,dishes);
        return Result.success(dishes);
    }

}
